import time

from models import Model


# 继承自Model的Todo类
class Todo(Model):
    @classmethod
    def new(cls, form, user_id=-1):
        t = cls(form, user_id)
        t.save()
        return t

    def __init__(self, form, user_id=-1):
        self.id = form.get('id', None)
        self.task = form.get('task', '')
        self.completed = False
        # 和别的数据关联的方式,用user_id表明他的user实例
        self.user_id = form.get('user_id', user_id)
        # 添加创建时间和修改时间
        self.created_time = form.get('created_time', None)
        self.updated_time = form.get('updated_time', None)
        if self.created_time is None:
            self.created_time = int(time.time())
            self.updated_time = self.created_time

    # 还应该添加时间戳

    @classmethod
    def complete(cls, id, completed):
        """
        用起来很方便
        Todo.complete(1,True)
        Todo.complete(2,False)
        """
        t = cls.find_by(id=id)
        t.completed = completed
        t.save()
        return t

    def ct(self):
        format = '%H:%M:%S'
        value = time.localtime(self.created_time)
        dt = time.strftime(format, value)
        return dt
